package com.itlong.cloud.utils.words;

import com.itlong.cloud.POJO.DTO.common.Article;
import com.itlong.cloud.POJO.DTO.common.ResponseNewMessage;
import com.itlong.cloud.POJO.DTO.common.ResponseTextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.Writer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信消息工具类
 *
 * @author Jiaqi.X
 * @version 1.0
 * @date 2016-12-21 14:50:24
 */
public class WechatMessageUtil {
    /**
     * 返回消息类型：文本
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";

    /**
     * 返回消息类型：音乐
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

    /**
     * 返回消息类型：图文
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";

    /**
     * 请求消息类型：文本
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";

    /**
     * 请求消息类型：图片
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

    /**
     * 请求消息类型：链接
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";

    /**
     * 请求消息类型：地理位置
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

    /**
     * 请求消息类型：音频
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

    /**
     * 请求消息类型：推送
     */
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";

    /**
     * 事件类型：subscribe(订阅)
     */
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

    /**
     * 事件类型：unsubscribe(取消订阅)
     */
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

    /**
     * 事件类型：CLICK(自定义菜单点击事件)
     */
    public static final String EVENT_TYPE_CLICK = "CLICK";



    /**
     * 解析微信发来的请求（XML）
     *
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();
        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());
        // 释放资源
        inputStream.close();
        inputStream = null;
        return map;
    }

    /**
     * 文本消息对象转换成xml
     *
     * @param responseTextMessage 文本消息对象
     * @return xml
     */
    public static String textMessageToXml(ResponseTextMessage responseTextMessage) {
        xstream.alias("xml", responseTextMessage.getClass());
        return xstream.toXML(responseTextMessage);
    }

    /**
     * 图文消息对象转换成xml
     *
     * @param responseNewMessage 图文消息对象
     * @return xml
     */
    public static String newsMessageToXml(ResponseNewMessage responseNewMessage) {
        xstream.alias("xml", responseNewMessage.getClass());
        xstream.alias("item", new Article().getClass());

        return xstream.toXML(responseNewMessage);
    }


    /**
     * 扩展xstream，使其支持CDATA块
     *
     */
    private static XStream xstream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;
                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                    if (name.equals("CreateTime")||name.equals("ArticleCount")){
                        this.cdata = false;
                    }else{
                        this.cdata = true;
                    }
                }
                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });


    // 与接口配置信息中的Token要一致
    private static String token = "weixin_101";

    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        boolean isEqual=false;
        String[] arr = new String[] { token, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);

        //三个参数组合成一个字符串
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        String tmpStr = null;
        //进行SHA1加密，返回16进制字符串
        tmpStr=encryptSHA1(content.toString());

        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        if(tmpStr!=null&&tmpStr.equals(signature)){
            isEqual=true;
        }else{
            isEqual=false;
        }
        content = null;

        return isEqual;
    }
    /**
     * SHA1加密
     *
     * @param data
     * @return
     */
    public static String encryptSHA1(String data){
        String str=null;
        try {
            // 获得SHA1摘要算法的 MessageDigest 对象
            MessageDigest md=MessageDigest.getInstance("SHA-1");
            // 使用指定的字节更新摘要
            md.update(data.getBytes());
            //获得密文
            byte[] bytes=md.digest();
            //字节数组转化为16进制字符串
            str=bytesToHexString(bytes);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }
    /**
     * 字节数组转化为16进制字符串
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes){
        StringBuffer sb=new StringBuffer();
        if(bytes==null||bytes.length<=0){
            return null;
        }
        for(int i=0;i<bytes.length;i++){
            int temp=bytes[i]&0xFF;//与运算，将byte转化为整型
            String hex=Integer.toHexString(temp);//int型转化为16进制字符串
            if(hex.length()<2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
